package com.tomise.core.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.druid.pool.DruidDataSource;
import com.tomise.core.page.Page;

/**
 * 核心dao层的基类
 * @author meigang
 * @date 2015-08-15
 * @version 1.0
 */
public abstract class MapperBaseDao<T> {
	@Autowired
	protected SqlSessionTemplate sqlSession;
	@Autowired
	protected DruidDataSource druidDataSource;
	/**
	 * 分页方法
	 * @param page 当前页
	 * @param rows 大小
	 * @param select 查询列
	 * @param tableWhere 查询表和where
	 * @param orderBy 排序 
	 * @param array 参数
	 * @return
	 */
	public Page page(Integer page, Integer size, String select,
			String tableWhere, String orderBy, Object[] array) {
		String sql = select + tableWhere + orderBy +" limit "+(page-1)*size +","+size;
		String sqlCount = "select count(1) count " + tableWhere;
		QueryRunner query = new QueryRunner();
		Page p = new Page();
		Connection conn = null;
		try {
			conn = druidDataSource.getConnection();
			int records = 0;
			int total = 0;
			List<Map<String, Object>> list = query.query(conn, sql, array,new MapListHandler());
			p.setList(list);
			List<Map<String,Object>> c = query.query(conn, sqlCount, array,new MapListHandler());
			if(c.size()==1){
				records = Integer.parseInt(c.get(0).get("count").toString());
				p.set_records(records);
			}
			if(records%size==0){
				total = records/size;
			}else{
				total = records/size + 1;
			}
			p.set_total(total);
			p.set_page(page);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return p;
	} 
	/**
	 * selectList
	 * @param sqlId 指向mybatis的xml文件中的sql的id
	 * @param p参数
	 * @return List<Object>
	 */
	public List<T> selectList(String sqlId,Object p){
		return sqlSession.selectList(sqlId,p);
	}
	
	public List<T> selectList(String sqlId){
		return sqlSession.selectList(sqlId);
	}
	
	public void save(String sqlId){
		sqlSession.insert(sqlId);
	}
	
	public void save(String sqlId,Object p){
		sqlSession.insert(sqlId,p);
	}
	
	public void update(String sqlId){
		sqlSession.update(sqlId);
	}
	
	public void update(String sqlId,Object p){
		sqlSession.update(sqlId,p);
	}
	
	public void delete(String sqlId){
		sqlSession.delete(sqlId);
	}
	
	public void delete(String sqlId,Object p){
		sqlSession.delete(sqlId,p);
	}
	
	public T selectOne(String sqlId){
		return sqlSession.selectOne(sqlId);
	}
	
	public T selectOne(String sqlId,Object p){
		return sqlSession.selectOne(sqlId,p);
	}
}
